package com.demo.service;

import com.demo.dao.UserRepository;
import com.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User addUser(User user){
        return userRepository.save(user);
    }

    public void delUserById(Long id){
        userRepository.deleteById(id);
    }

    @Transactional(timeout = 10)
    public void updateUser(User user){
        User resultUser = userRepository.getOne(user.getId());
        resultUser.setUsername(user.getUsername());
        resultUser.setAddress(user.getAddress());
        userRepository.flush();
    }

    @Transactional(timeout = 10)
    public Optional<User> getUserById(Long id){
        return userRepository.findById(id);
    }

    public List<User> getAll(){
        return userRepository.findAll();
    }

    public List<User> getAllByUsernameLike(String name){
        return userRepository.findAllByUsernameLike(name);
    }

 }
